<template>
  <div class="lesson-page">
    <div class="page-header">
      <h2>分享列表</h2>
      <el-button type="primary" @click="handleAdd">发布课程</el-button>
    </div>

    <!-- 搜索区域 -->
    <div class="search-section">
      <el-form :inline="true" :model="searchParams">
        <el-form-item>
          <el-input
            v-model="searchParams.keyword"
            placeholder="请输入关键词"
            clearable
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 列表区域 -->
    <div class="list-section">
      <!-- 加载中状态 -->
      <div v-if="isLoading" class="state-message">
        加载中...
      </div>

      <!-- 无数据状态 -->
      <div v-else-if="!lessons.length" class="state-message">
        暂无课程数据
      </div>

      <!-- 课程列表 -->
      <div v-else class="lesson-list">
        <div v-for="lesson in lessons" :key="lesson.id" class="lesson-item">
          <div class="lesson-header">
            <h3 class="title" @click="handleViewDetail(lesson)">{{ lesson.title }}</h3>
          </div>
          <div class="lesson-info">
            <div class="author-info">
              <img 
                :src="lesson.user?.head || '/default-avatar.png'"
                :alt="lesson.user?.realname"
                class="author-avatar"
              />
              <span>作者: {{ lesson.user?.realname }}</span>
              <span>发布时间: {{ formatTime(lesson.publishTime) }}</span>
              <span v-if="lesson.type" class="type-tag">
                类型: {{ lesson.type}}
              </span>
              <div class="actions" style="display: flex; justify-content: flex-end;">
                <button 
                  class="action-btn edit" 
                  @click="handleEdit(lesson)" 
                  v-if="(isAdmin || userId === lesson.userId)"
                >
                  编辑
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="searchParams.page"
        v-model:page-size="searchParams.rows"
        :page-sizes="pageSizes"
        :total="totalCount"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加编辑器组件 -->
    <LessonEditor
      v-model:visible="editorVisible"
      :edit-data="editData"
      :is-edit="isEdit"
      @onSubmit="handleEditorSubmit"
      @onClose="handleEditorClose"
    />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessageBox, ElMessage } from 'element-plus'
import axios from '../plugins/axios'
import LessonEditor from '../components/LessonEditor.vue'

const router = useRouter()
const lessons = ref([])
const totalCount = ref(0)
const currentPage = ref(1)
const pageSize = ref(5)
const pageSizes = [5, 10, 20, 50]
const isLoading = ref(false)

// 添加编辑器相关的响应式变量
const editorVisible = ref(false)
const editData = ref(null)
const isEdit = ref(false)

// 添加当前用户ID
const currentUserId = ref(parseInt(localStorage.getItem('userId')))

// 初始化搜索参数
const searchParams = ref({
  keyword: '',
  page: 1,
  rows: 5,
  sortWay: 'DESC',
  sortColumn: 'publish_time'
})
const isAdmin = localStorage.getItem('isAdmin') === '1'
const userId = Number(localStorage.getItem('userId'))
// 获取课程列表数据
const fetchLessonData = async () => {
  isLoading.value = true
  try {
    const response = await axios.post('/lesson/queryByCondition', searchParams.value)
    if (response.data.code === 1) {
      lessons.value = response.data.data
      totalCount.value = response.data.total
    } else {
      ElMessage.error(response.data.msg || '获取课程列表失败')
    }
  } catch (error) {
    console.error('获取课程列表失败:', error)
    ElMessage.error('获取课程列表失败')
  } finally {
    isLoading.value = false
  }
}

// 搜索方法
const handleSearch = () => {
  currentPage.value = 1
  fetchLessonData()
}

const handleEditorClose = () => {
  editorVisible.value = false
  editData.value = null
}

// 重置搜索
const resetSearch = () => {
  searchParams.value = {
    keyword: '',
    page: 1,
    rows: 5,
    sortWay: 'DESC',
    sortColumn: 'publish_time'
  }
  fetchLessonData()
}

// 处理每页显示数量变化
const handleSizeChange = (val) => {
  searchParams.value.rows = val
  fetchLessonData()
}

// 处理页码变化
const handleCurrentChange = (val) => {
  searchParams.value.page = val
  fetchLessonData()
}

// 查看详情
const handleViewDetail = (lesson) => {
  router.push(`/knowledge/lesson/${lesson.id}`)
}

// 格式化时间
const formatTime = (time) => {
  if (!time) return ''
  const date = new Date(time)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}`
}

// 添加发布按钮处理方法
const handleAdd = () => {
  editData.value = null
  isEdit.value = false
  editorVisible.value = true
}

// 添加编辑器提交回调
const handleEditorSubmit = () => {
  fetchLessonData() // 刷新列表
}

// 添加编辑处理方法
const handleEdit = (lesson) => {
  editData.value = {
    id: lesson.id,
    title: lesson.title,
    type: lesson.type,
    content: lesson.content,
    attachment: lesson.attachment,
    attachmentName: lesson.attachmentName
  }
  isEdit.value = true
  editorVisible.value = true
}

onMounted(() => {
  fetchLessonData()
})
</script>

<style scoped>
.lesson-page {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 0 20px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
  font-size: 20px;
}

.search-section {
  margin-bottom: 20px;
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.list-section {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.lesson-item {
  border-bottom: 1px solid #ebeef5;
  padding: 15px 0;
}

.lesson-item:last-child {
  border-bottom: none;
}

.lesson-header {
  margin-bottom: 10px;
}

.title {
  margin: 0;
  font-size: 16px;
  color: #303133;
  cursor: pointer;
}

.title:hover {
  color: #409EFF;
}

.lesson-info {
  font-size: 14px;
  color: #606266;
}

.author-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.author-avatar {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  object-fit: cover;
}

.type-tag {
  padding: 2px 6px;
  background-color: #f0f9eb;
  color: #67c23a;
  border-radius: 4px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.state-message {
  text-align: center;
  padding: 40px 0;
  color: #909399;
}

/* 添加修改按钮样式 */
.el-button--link {
  padding: 0;
  height: auto;
  &:hover {
    color: #409EFF;
    text-decoration: underline;
  }
}
.actions {
  display: flex;
  gap: 0.5rem;
  justify-content: flex-end;  /* 靠右对齐 */
  margin-left: auto;  /* 推到最右边 */
}

.action-btn {
  padding: 0.25rem 0.75rem;
  border: 1px solid #DFE1E6;
  background-color: white;
  border-radius: 3px;
  cursor: pointer;
  font-size: 0.9rem;
  transition: all 0.2s;
}

.action-btn.assign {
  background-color: #fff;
  color: #409EFF;
  border: 1px solid #409EFF;
}

.action-btn.assign:hover {
  background-color: #ecf5ff;
  color: #409EFF;
  border-color: #409EFF;
}

.action-btn.edit {
  color: #67C23A;
  border: 1px solid #67C23A;
  text-align: right;
}

.action-btn.edit:hover {
  background-color: #f0f9eb;
  border-color: #67C23A;
  color: #67C23A;
}

.action-btn.delete {
  color: #F56C6C;
  border: 1px solid #F56C6C;
}

.action-btn.delete:hover {
  background-color: #fef0f0;
  border-color: #F56C6C;
  color: #F56C6C;
}
</style> 